<template>
  <div v-loading="loading" class="theme-content-item" style="position: relative;">
    <div class="padding-20px form-style">
      <div class="left-title">{{ title }}</div>
      <el-form ref="docFormRef" label-width="120px" :model="form" :rules="rules"
        style="margin-top: 40px">
        <el-row style="display: flex;justify-content:start">
          <el-col :span="8">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="margin-left: 20%">
            <el-form-item label="课程类型" prop="courseType">
              <el-cascader v-model="form.courseType" placeholder="请选择关联课程类型" :options="data.courseList"
                           :props="{label:'name',value:'id',children:'children',emitPath:false}"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="类型" prop="type">
              <el-select clearable v-model="form.type" placeholder="请选择类型">
                <el-option v-for="item in data.docTypeList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="margin-left: 20%">
            <el-form-item label="老师" prop="teacherId">
              <el-select clearable v-model="form.teacherId" placeholder="请选择老师">
                <el-option v-for="item in data.teacherList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="年份" prop="year">
              <el-date-picker
                  v-model="form.year"
                  value-format="YYYY"
                  type="year"
                  placeholder="请选择年份"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="margin-left: 20%">
            <el-form-item label="排序" prop="orderNum">
              <el-input type="number" v-model="form.orderNum" placeholder="请输入排序号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="说明">
              <el-input type="textarea" v-model="form.remark" placeholder="请输入说明"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="margin-left: 20%">
            <el-form-item label="状态" prop="publishedFlag">
              <el-radio v-model="form.publishedFlag" :label="1">上架</el-radio>
              <el-radio v-model="form.publishedFlag" :label="0">下架</el-radio>
            </el-form-item>
          </el-col>
        <el-col :span="8">
          <el-form-item label="上传文件" prop="url">
            <div class="flex-column">
              <el-upload class="avatar-uploader" name="fileList" :action="$uploadUrl" :headers="headers" :show-file-list="false"
                         :on-success="handleUploadSuccess" :on-error="handleUploadError" accept=".xls .xlsx .doc .docx .pdf .ppt .pptx">
                <el-button type="primary">点击上传</el-button>
              </el-upload>
              <div v-if="form.url" class="flex-jc-s-b" style="width: 400px;font-size: 12px;font-weight: 400;cursor: pointer">
                <span>{{form.originFileName}}</span>
                <el-icon @click="form.url = '';form.originFileName=''" size="12" color="#E65D6E"><Delete /></el-icon>
              </div>
            </div>
          </el-form-item>
        </el-col>
        </el-row>
      </el-form>
      <div style=" position: fixed; bottom: 5%; left: 45%" class="flex-jc-s-b">
        <el-button size="small" @click="goBack()">
          <svg-icon icon-class="back" class="el-input__icon input-icon" />
          <span style="margin-left: 5px;">关 闭</span>
        </el-button>
        <el-button size="small" style="margin-left: 20px;" type="primary" @click="save">
          <svg-icon icon-class="save" class="el-input__icon input-icon" />
          <span style="margin-left: 5px;">保 存</span>
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import {tableItem} from './const'
import {addDoc, editDoc, getDocDetail} from '@/api/resource/doc'
import {listDictItemByCode} from '@/api/config/dic'
import {listTeacher} from '@/api/teacher'
import {pagingDoc} from '@/api/resource/doc'
import {getToken} from '@/utils/auth'
const headers = ref({ Authorization: "Bearer " + getToken() });
const { proxy } = getCurrentInstance();
const route = useRoute()
const router = useRouter()
const routeQuery = reactive(route.query)
const loading = ref(false)
const title = ref('');
const isAdd = ref(false);
const data = reactive({
  courseList: [],
  docTypeList: [],
  teacherList: [],
  docList: [],
})
const form = reactive({
  id: null,
  orderNum: '',
  name: '',
  courseType: '',
  type: '',
  teacherId: '',
  year: '',
  publishedFlag: 1,
  url: '',
  remark: '',
  originFileName: ''
})

const rules = ({
  orderNum: [{ required: true, message: '请输入排序号', trigger: 'blur' }],
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  courseType: [{ required: true, message: '请选择课程类型', trigger: 'blur' }],
  type: [{ required: true, message: '请选择类型', trigger: 'blur' }],
  teacherId: [{ required: true, message: '请选择老师', trigger: 'blur' }],
  url: [{ required: true, message: '请选择文件', trigger: 'blur' }],
  year: [{ required: true, message: '请选择年份', trigger: 'blur' }],
  publishedFlag: [{ required: true, message: '请选择状态', trigger: 'blur' }],
})

// 详情
const initDetail = (row) => {
  getDocDetail(row.id || route.query.id).then((res) => {
    Object.keys(form).forEach((key) => { form[`${key}`] = res.data[`${key}`] })
    form.url = res.data.url
  })
}
const initData = () => {
  listDictItemByCode({typeCode: 'courseTypeCode'}).then(res => {
    data.courseList = res.rows
  })
  listDictItemByCode({typeCode: 'docTypeCode'}).then(res => {
    data.docTypeList = res.rows
  })
  listTeacher({}).then(res => {
    data.teacherList = res.rows
  })
  pagingDoc({}).then(res => {
    data.docList = res.rows
  })
}

const save = () => {
  proxy.$refs["docFormRef"].validate(valid => {
    if (valid) {
      loading.value = true
      if (isAdd.value) {
        addDoc(form).then(res => {
          if (res.code === 200) {
            loading.value = false
            goBack()
            tableItem.pageInfo.paging()
            ElMessage.success('新增成功');
          }
        })
      } else {
        editDoc(form).then(res => {
          if (res.code === 200) {
            loading.value = false
            goBack()
            tableItem.pageInfo.paging()
            ElMessage.success('修改成功');
          }
        })
      }
    }
  })
}
function handleUploadSuccess(response) {
  form.url = response.data[0].url
  form.originFileName = response.data[0].fileName
  ElMessage({ message: "上传成功", type: 'success' })
}
function handleUploadError(Error) {
  ElMessage.error("上传失败")
}
function goBack() {
  proxy.$tab.closeOpenPage();
  router.go(-1)
}

onMounted(() => {
  let titleMap = {
    add: '新增资料',
    edit: '修改资料',
  }
  routeQuery.type ? title.value = titleMap[routeQuery.type] : ''
  routeQuery.type == 'edit' ? initDetail(route.query) : ''
  isAdd.value = routeQuery.type == 'add'
  initData()
})
</script>
